from flask import Flask, request, jsonify
from threading import Thread
import time
from pd_proxy import DrissionPageDemo, get_random_proxy

app = Flask(__name__)

# 初始化代理控制器
dp = DrissionPageDemo()
dp.get_page()
dp.load_extensions_default_config()

# ========== 后台代理切换线程 ==========
def auto_switch_proxy(interval=300):
    last_ip = None
    while True:
        ip, port, user, pwd = get_random_proxy()
        if not ip:
            print("[x] 获取代理失败，重试中...")
            time.sleep(interval)
            continue

        print(f"[*] 切换代理: {ip}:{port}")
        if dp.switch_ip(ip, port, user, pwd):
            try:
                dp.page.get("https://ip.cn")
                current_ip = dp.check_ip()
                if current_ip != last_ip:
                    print(f"[+] IP切换成功: {current_ip}")
                    last_ip = current_ip
                else:
                    print("[-] IP未改变")
            except Exception as e:
                print("[x] 检查 IP 失败:", e)
        else:
            print("[x] 代理切换失败")
        time.sleep(interval)

# 启动代理切换后台线程
Thread(target=auto_switch_proxy, daemon=True).start()

# ========== API 接口 ==========

@app.route("/fetch", methods=["GET", "POST"])
def fetch():
    url = request.args.get("url") or (request.json or {}).get("url")
    if not url:
        return jsonify({"error": "缺少参数url"}), 400

    try:
        # 打开新标签页访问 URL
        new_page = dp.page.new_tab()
        new_page.get(url)
        new_page.wait.load_start()

        # 获取页面 HTML
        html = new_page.html

        # ✅ 关闭新开的标签页，释放资源
        new_page.close()

        return jsonify({
            "url": url,
            "html": html,
            "status": "success"
        })

    except Exception as e:
        return jsonify({
            "error": str(e),
            "status": "fail"
        }), 500


@app.route("/ip")
def current_ip():
    try:
        ip = dp.check_ip()
        return jsonify({"ip": ip})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    app.run(port=5566)
